package com.yao.mybatis.sqlsession;

import com.yao.mybatis.config.Configuration;
import com.yao.mybatis.config.MappedStatement;
import com.yao.mybatis.executor.CachingExecutor;
import com.yao.mybatis.executor.SimpleExecutor;

import java.util.List;

/**
 * @author Administrator
 */
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <T> T selectOne(String msId, Object parm) {
        // 直接调用selectList方法
        List<T> result = selectList(msId, parm);
        if (result == null || result.size() == 0) {
            return null;
        } else if (result.size() == 1) {
            return result.get(0);
        } else {
            throw new RuntimeException("查询出多个结果");
        }
    }

    @Override
    public <E> List<E> selectList(String msId, Object param) {
        //根据statementId获取mappedStatement
        MappedStatement mappedStatement = configuration.getMappedStatement(msId);
        //调用executor来执行具体的查询
        CachingExecutor cachingExecutor = new CachingExecutor(new SimpleExecutor());
        //CachingExecutor.query[查询一级缓存]->
        // BaseExecutor.query(SimpleExecutor继承的)[查询二级缓存]->
        // SimpleExecutor.queryFromDataBase[查询数据库]
        return cachingExecutor.query(mappedStatement,configuration,param);
    }
}
